package com.mikelouis.test.scala.proginscala.chapter4

/**
 * Created by yuazhu on 12/18/2014.
 */
class ChecksumAccumulator {
  private var sum = 0

  def add(b: Byte): Unit = sum += b

  // 带有大括号但没有等号的，在本质上当作是显式定义结果类型为Unit的方法
  def add2(b: Byte) {
    sum += b
  }

  def checksum(): Int = {
    ~(sum & 0xFF) + 1
  }

}

object ChecksumAccumulator {
  private val cache = scala.collection.mutable.Map[String, Int]()

  def calculate(s: String): Int =
    if (cache.contains(s))
      cache(s)
    else {
      // 关键字new只用来实例化类，所以这里创造的新对象是ChecksumAccumulator类的一个实例，而不是同名的单例对象
      val acc = new ChecksumAccumulator
      for (c <- s)
        acc.add(c.toByte)
      val cs = acc.checksum()
      cache += (s -> cs)
      cs
    }

  def main(args: Array[String]) {
    print(ChecksumAccumulator.calculate("Every value is an object."))
  }
}
